<?php

require_once('LightOAuth2.php');
// sample for Facebook Graph API using OAuth 2.0 draft
define('CLIENT_ID','753278233436.apps.googleusercontent.com');
define('CLIENT_SECRET','S0MwjxS3VBpFuJOpQx7Vt0sG');

define('SCOPE','https://www.google.com/m8/feeds/ https://www.googleapis.com/auth/userinfo.email');
$entry = array('authorize'=>'https://accounts.google.com/o/oauth2/auth',
	       'access_token'=>'https://accounts.google.com/o/oauth2/token');

// path for the application script'
define('CALLBACK','http://localhost/lightoauth2/connectGoogle.php');

$oauth = new LightOAuth2(CLIENT_ID, CLIENT_SECRET);
   
session_start();
if (!isset($_SESSION['access_token'])) {
  if (!isset($_GET['code'])) { // get authorization code
    $opts = array('scope'=>SCOPE);
    $url = $oauth->getAuthUrl($entry['authorize'], CALLBACK, $opts);
    header("Location: " . $url);
    exit();
  }
  // get access token
  $obj = $oauth->getToken($entry['access_token'], CALLBACK,
			  $_GET['code'], 'json');
  $_SESSION['access_token'] = $obj->access_token;
}

//echo 'Access token:' . $obj->access_token . $_SESSION['access_token'] . '<br />';
$oauth->setToken($_SESSION['access_token']);

// get user info
$url = "https://www.google.com/m8/feeds/contacts/default/full";
$response = $oauth->fetch($url);
if($response!=''){
	preg_match('/<author><name>([^<]*)<\/name><email>([^<]*)<\/email><\/author>/', $response, $out);
	if(count($out[1])>0){
		/* found the user fullname and email */
		$fullName = $out[1];
		$email = $out[2];
		echo "Login info: Full name: <b>$fullName</b> - Email: <b>$email</b>";
	}
}

?>
